<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LandingCompany\StoreLandingCompanyRequest;
use App\Http\Requests\Admin\LandingCompany\UpdateLandingCompanyRequest;
use App\Models\AdminOperationLog;
use App\Models\LandingCompany;
use Illuminate\Http\JsonResponse;

class LandingCompanyController extends Controller
{
    public function index(): JsonResponse
    {
        $companies = LandingCompany::orderByDesc('created_at')->get();

        return response()->json([
            'code' => 0,
            'message' => '获取落地公司列表成功',
            'data' => [
                'items' => $companies,
                'total' => $companies->count(),
            ],
        ]);
    }

    public function store(StoreLandingCompanyRequest $request): JsonResponse
    {
        $validated = $request->validated();

        $validated['billing_categories'] = array_values(array_filter(array_map('trim', $validated['billing_categories'])));
        $company = LandingCompany::create($validated);

        $adminUser = $request->user('admin');

        AdminOperationLog::log(
            $adminUser ? $adminUser->id : null,
            'landing-company.create',
            'landing_company',
            LandingCompany::class,
            $company->id,
            '创建落地公司',
            $validated,
            ['landing_company_id' => $company->id]
        );

        return response()->json([
            'code' => 0,
            'message' => '落地公司创建成功',
            'data' => $company->fresh(),
        ], 201);
    }

    public function update(UpdateLandingCompanyRequest $request, LandingCompany $landingCompany): JsonResponse
    {
        $validated = $request->validated();

        $validated['billing_categories'] = array_values(array_filter(array_map('trim', $validated['billing_categories'])));
        $landingCompany->fill($validated);
        $landingCompany->save();

        $adminUser = $request->user('admin');

        AdminOperationLog::log(
            $adminUser ? $adminUser->id : null,
            'landing-company.update',
            'landing_company',
            LandingCompany::class,
            $landingCompany->id,
            '更新落地公司信息',
            $validated,
            ['landing_company_id' => $landingCompany->id]
        );

        return response()->json([
            'code' => 0,
            'message' => '落地公司信息已更新',
            'data' => $landingCompany->fresh(),
        ]);
    }
}
